<template>
  <view class="chat-container">
    <scroll-view scroll-y class="message-list" :scroll-top="scrollTop" :scroll-into-view="scrollIntoView" @scroll="handleScroll">
      <view v-for="(msg, index) in messages" :key="index" :id="'msg-' + index" class="message-item" :class="msg.role">
        <view class="bubble">{{ msg.content }}</view>
        <view class="timestamp">{{ msg.time }}</view>
      </view>
      <view :id="bottomAnchor" style="height: 20rpx" />
    </scroll-view>

    <view class="loading-indicator" v-if="loading">正在请求中...</view>

    <view class="input-bar">
      <textarea
        v-model="inputText"
        class="input-box"
        placeholder="请输入内容"
        @confirm="sendMessage"
        @keyboardheightchange="handleKeyboard"
        auto-height
        confirm-type="send"
      />
      <button class="send-btn" @click="sendMessage">发送</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'

interface Message {
  role: 'user' | 'assistant'
  content: string
  time: string
}

const apiKey = ref('')
const messages = ref<Message[]>([])
const inputText = ref('')
const loading = ref(false)
const scrollTop = ref(0)
const scrollIntoView = ref('')
const bottomAnchor = 'bottom'

// 时间格式化
const formatTime = () => {
  const now = new Date()
  return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
}

// 获取缓存
const loadCache = () => {
  const cache = uni.getStorageSync('chat-messages')
  if (cache) {
    messages.value = cache
    nextTick(() => scrollToBottom())
  }
}

// 缓存更新
const saveCache = () => {
  uni.setStorageSync('chat-messages', messages.value)
}

// 滚动到底部
const scrollToBottom = () => {
  scrollIntoView.value = 'msg-' + (messages.value.length - 1)
}

onMounted(async () => {
  loadCache()
  await getApikey()
})

function getApikey(): Promise<void> {
  return new Promise((resolve, reject) => {
    uni.request({
      url: 'https://xrqr0h0x1w.gzg.sealos.run/get_apikey',
      method: 'GET',
      success: (res) => {
        const key = res.data?.data?.data?.deepseek
        if (key) {
          apiKey.value = key
          resolve()
        } else {
          uni.showToast({ title: 'API 密钥为空', icon: 'none' })
          reject('空密钥')
        }
      },
      fail: (err) => {
        uni.showToast({ title: '密钥获取失败', icon: 'none' })
        reject(err)
      }
    })
  })
}

const sendMessage = async () => {
  const text = inputText.value.trim()
  if (!text || loading.value) return

  messages.value.push({ role: 'user', content: text, time: formatTime() })
  inputText.value = ''
  loading.value = true
  saveCache()
  nextTick(() => scrollToBottom())

  try {
    const result = await uni.request({
      url: 'https://api.deepseek.com/v1/chat/completions',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + apiKey.value,
      },
      data: {
        model: "deepseek-chat",
        messages: messages.value.map(({ role, content }) => ({ role, content }))
      },
    })

    const reply = result.data?.choices?.[0]?.message?.content || '无回复'
    messages.value.push({ role: 'assistant', content: reply, time: formatTime() })
    saveCache()
    nextTick(() => scrollToBottom())
  } catch (err) {
    uni.showToast({ title: '请求失败', icon: 'none' })
    console.error("请求错误：", err)
  } finally {
    loading.value = false
  }
}

const handleScroll = () => {
  // 可用于处理用户滚动加载历史等逻辑
}

const handleKeyboard = (e: any) => {
  scrollToBottom()
}
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20rpx;
  box-sizing: border-box;
}

.message-item {
  margin-bottom: 30rpx;
  display: flex;
  flex-direction: column;
  max-width: 100%;
  word-break: break-word;
}

.message-item.user {
  align-self: flex-end;
  align-items: flex-end;
}

.message-item.assistant {
  align-self: flex-start;
  align-items: flex-start;
}

.bubble {
  padding: 20rpx 25rpx;
  border-radius: 24rpx;
  font-size: 30rpx;
  line-height: 1.6;
  white-space: pre-wrap;
}

.user .bubble {
  background-color: #95ec69;
  margin-right: 5rpx; /* 改为靠右边 5rpx */
  border-top-right-radius: 0;
}

.assistant .bubble {
  background-color: #fff;
  margin-left: 5rpx; /* 改为靠左边 5rpx */
  border-top-left-radius: 0;
}

.timestamp {
  font-size: 24rpx;
  color: #888;
  margin-top: 10rpx;
}

.input-bar {
  display: flex;
  padding: 10rpx 20rpx;
  background: #fff;
  align-items: flex-end;
  border-top: 1px solid #ddd;
}

.input-box {
  flex: 1;
  min-height: 80rpx;
  max-height: 300rpx;
  background: #f7f7f7;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 28rpx;
  line-height: 1.4;
}

.send-btn {
  margin-left: 20rpx;
  padding: 0 32rpx;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 28rpx;
  background-color: #07c160;
  color: white;
  border-radius: 12rpx;
}

.loading-indicator {
  position: absolute;
  bottom: 140rpx;
  left: 50%;
  transform: translateX(-50%);
  background: #eee;
  padding: 10rpx 20rpx;
  border-radius: 10rpx;
  font-size: 24rpx;
  color: #666;
}
</style>
